package com.bruce.starts.demo.commonerror.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * @author luotuan
 * @Description
 * @create 2021-05-06 11:07
 **/
@Slf4j
public class ThreadPoolExecutorDemo {
    public static void main(String[] args) throws InterruptedException {
        new ThreadPoolExecutorDemo().right();
    }

    private int right() throws InterruptedException {
        AtomicInteger atomicInteger = new AtomicInteger();
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 5, 5, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10), new ThreadFactoryBuilder().setNameFormat("demo-thread-%d").build(),
                new ThreadPoolExecutor.AbortPolicy());
        printStats(poolExecutor);
        IntStream.rangeClosed(1, 20).forEach(i -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            int id = atomicInteger.incrementAndGet();
            try {
                poolExecutor.submit(() -> {
                    log.info("{} started", id);
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    }
                    catch (InterruptedException e) {

                    }
                    log.info("{} finished", id);
                });
            }
            catch (Exception e) {
                log.error("error submitting task {}", id, e);
                atomicInteger.decrementAndGet();
            }
        });
        TimeUnit.SECONDS.sleep(60);
        return atomicInteger.intValue();
    }

    private void printStats(ThreadPoolExecutor threadPoolExecutor) {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            log.info("=====================================");
            log.info("Pool Size:{} ", threadPoolExecutor.getPoolSize());
            log.info("Active Threads: {}", threadPoolExecutor.getActiveCount());
            log.info("Number of Tasks Completed: {}", threadPoolExecutor.getCompletedTaskCount());
            log.info("Number of Tasks in Queue: {}", threadPoolExecutor.getQueue().size());
            log.info("=====================================");
        }, 0, 1, TimeUnit.SECONDS);
    }
}
